package com.cn.demo3;

import java.lang.reflect.Field;

/**
 * Field类用于给成员变量赋值的方法
 * 1. void set(Object obj, Object value)赋值
 * 2. Object get(Object obj)获取值
 */
public class ReflectDemo2 {
    public static void main(String[] args) throws NoSuchFieldException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        method1();
        method2();
    }

    //使用get方法获取值
    private static void method2() throws ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        //1.获取class对象
        Class<?> clazz = Class.forName("com.cn.demo3.Student");
        //2.获取指定成员变量的Field对象
        Field money = clazz.getDeclaredField("money");
        //3.取消访问检查
        money.setAccessible(true);
        //4.使用get方法来获取值
        //4.1创建一个对象
        Student student = (Student) clazz.newInstance();
        //4.2获取指定对象的money的值
        Object object = money.get(student);
        System.out.println(object);
    }

    //使用set方法设置值
    private static void method1() throws ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        //void set(Object obj, Object value)：给obj对象的成员变量赋值为value
        //1.获取class对象
        Class clazz = Class.forName("com.cn.demo3.Student");

        //2.获取name这个Field对象
        Field field = clazz.getField("name");

        //3.利用set方法进行赋值.
        //3.1先创建一个Student对象
        Student student = (Student) clazz.newInstance();
        //3.2有了对象才可以给指定对象进行赋值
        field.set(student,"zhangsan");
        System.out.println(field.get(student));
        System.out.println(student);
    }
}
